package com.yykj.drup.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yykj.common.util.RandomUtil;
import com.yykj.common.vo.ResultVO;
import com.yykj.drup.client.WiFenXiaoOrder;
import com.yykj.drup.client.form.WiFenXiaoPayOrderFrom;
import com.yykj.drup.server.dto.PrescriptionStoreProductDto;
import com.yykj.drup.server.form.OrderForm;
import com.yykj.drup.server.mapper.OrderInfoDao;
import com.yykj.drup.server.model.*;
import com.yykj.drup.server.service.*;
import com.yykj.drup.server.service.feign.PayCenterServerFeign;
import com.yykj.drup.server.service.feign.WiFenXiaoServerFeign;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zengg
 * @since 2022-03-22
 */
@Service
@AllArgsConstructor
@Slf4j
public class OrderInfoServiceImp extends ServiceImpl<OrderInfoDao, OrderInfo> implements OrderInfoService {

    final OrderService orderService;
    final OrderInfoDao orderInfoDao;
    final ExpressService expressService;
    final OrderDetailsService orderDetailsService;
    final PayCenterServerFeign payCenterServerFeign;
    final WiFenXiaoServerFeign wiFenXiaoServerFeign;
    final StoreServiceImpl storeService;
    final ProductService productService;


    @Override
    @Transactional
    public void insertOrderByOrderForm(String orderNumber,OrderForm orderForm) {
        List<PrescriptionStoreProductDto> storeProductDtos = orderForm.getStoreProductDtos();
        if (!storeProductDtos.isEmpty()){
            //插入药店订单信息
            for (PrescriptionStoreProductDto storeProduct:storeProductDtos) {
                OrderInfo order = new OrderInfo();
                // 设置总订单号
                order.setOrderSysNum(orderNumber);
                //设置药店订单号
                order.setOrderStoreNum(RandomUtil.randomNumbers(12));
                order.setStoreId(storeProduct.getId());
                order.setStoreName(storeProduct.getShopName());
                order.setStoreHeadImgurl(storeProduct.getHeadimgurl());
                //order.setDeliveryAddressId(orderForm.getDeliveryAddressId());
                order.setFreightPrice(orderForm.getFreightPrice());
                order.setFreightType(orderForm.getFreightType());
                //order.setPayType(orderForm.getPayType());
                //设置药店订单金额
                BigDecimal storeOrderPrice = orderService.getStoreOrderPrice(storeProduct);
                order.setStoreProductCount(orderService.getStoreProductCount(storeProduct));
                order.setStoreProductPrice(storeOrderPrice);
                order.setOrderUserName(orderForm.getName());
                order.setOrderUserAddress(orderForm.getAddressDetail());
                order.setOrderUserPhone(orderForm.getMobile());
                order.setProvince(orderForm.getProvince());
                order.setCity(orderForm.getCity());
                order.setArea(orderForm.getArea());
               // order.setHospitalId(orderForm.getHospitalId());
                //order.setPrescriptionId(orderForm.getPrescriptionId());
                Integer id = this.insertOrder(order);
                if (id != 0){
                    //添加订单详情信息
                    List<OrderDetails> detailsList = orderDetailsService.orderDetailsInit(storeProduct);
                    orderDetailsService.insertOrderDetails(id,detailsList);
                }
            }
        }
    }

    @Override
    public Integer insertOrder(OrderInfo order) {
        orderInfoDao.insert(order);
        return order.getId();
    }

    @Override
    public List<OrderInfo> findStoreOrderBySysOrderId(String sysOrderNumber) {
        return orderInfoDao.findStoreListByOrderId(sysOrderNumber);
    }

    @Override
    public void weifenxiaoPlaceOrder(String orderNum) {
        Integer i = 0;
        //根据系统总订单号获取药店订单及商品信息
        List<OrderInfo> infoList = this.findStoreOrderBySysOrderId(orderNum);
        infoList.stream().forEach(info->{
            //获取订单商城药店ID
            Store store = storeService.getById(info.getStoreId());
            String storeId = store.getUserId();
            //获取订单商城药店药品数组
            List<String> itemids = new ArrayList<>();
            List<String> itemCount = new ArrayList<>();
            List<OrderDetails> orderDetails = info.getOrderDetails();
            orderDetails.stream().forEach(orderDetail->{
                Product product = productService.getById(orderDetail.getProductId());
                //获取药品对于第三方商城的标识
                itemids.add(product.getItemId());
                //获取药品购买的数量
                itemCount.add(orderDetail.getProductNumber().toString());
            });
            //封装下单参数
            WiFenXiaoPayOrderFrom from = WiFenXiaoPayOrderFrom.builder()
                .name(info.getOrderUserName())
                .mobile(info.getOrderUserPhone())
                .province(info.getProvince())
                .city(info.getCity())
                .area(info.getArea())
                .user_id(storeId)
                .address_detail(info.getOrderUserAddress())
                .item_id(itemids)
                .num(itemCount)
                .payment(info.getStoreProductPrice())
                    .build();
            log.info("发起微分销下单开始：{}", from);
            //发起微分销下单
            ResultVO<WiFenXiaoOrder> resultVO = wiFenXiaoServerFeign.payOrder(from);
            log.info("发起微分销下单结束：{}", resultVO);
            WiFenXiaoOrder voData = resultVO.getData();
            log.info("微分销下单返回数据：{}", voData);
            //获取第三方订单号
            String orgOrderNum = voData.getOrder_no();
            //设置药店订单，第三方订单号
            Boolean success = this.setOrderInfoOrgOrderNum(info.getOrderStoreNum(), orgOrderNum);
            log.info("设置药店订单，第三方订单号: {}", success);
            //订阅快递
            //HttpResult result = expressService.expressPoll(expressNo, info.getOrderUserPhone(), null);
            //log.info("订阅快递返回：{}", result);
        });
    }

    @Override
    public Boolean setOrderInfoOrgOrderNum(String orderStoreNum, String orgOrderNum) {
        LambdaUpdateWrapper<OrderInfo> wrapper = new LambdaUpdateWrapper<>();
        //设置快递单号，第三方订单号，
        wrapper.set(OrderInfo::getOrgOrderNum,orgOrderNum)
                .eq(OrderInfo::getOrderStoreNum,orderStoreNum);
        return this.update(wrapper);
    }

    @Override
    public Boolean setOrderInfoComNumber(String orgOrderNum,String expressName,String expressNo) {
        LambdaUpdateWrapper<OrderInfo> wrapper = new LambdaUpdateWrapper<>();
        //根据第三方订单号，设置订单物流信息
        wrapper.set(OrderInfo::getOrderComNumber,expressNo)
                .set(OrderInfo::getOrderCom,expressName)
                .eq(OrderInfo::getOrgOrderNum,orgOrderNum);
        return this.update(wrapper);
    }

    @Override
    public Boolean setOrderInfoComCheck(String orderComNum,String ischeck) {
        LambdaUpdateWrapper<OrderInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(OrderInfo::getOrderComCheck,ischeck)
                .set(OrderInfo::getOrderComCheckTime, LocalDateTime.now())
                .eq(OrderInfo::getOrderComNumber,orderComNum);
        return this.update(wrapper);
    }
    @Override
    public void setOrderStatusOK(String orderSysNum) {
        //查询系统订单是否有未确认收货
        LambdaUpdateWrapper<OrderInfo> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(OrderInfo::getOrderStoreCheck,0)
                .eq(OrderInfo::getOrderSysNum,orderSysNum);
        List<OrderInfo> orderInfoList = this.list(wrapper);
        if (orderInfoList.isEmpty()){
            //更新系统订单状态为：已完成
            LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper
                    .set(Order::getOrderStatus,3)
                    .eq(Order::getOrderSysNumber,orderSysNum);
            orderService.update(updateWrapper);
        }
    }
    @Override
    public Boolean setOrderInfoCheck(Integer id) {
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setId(id);
        orderInfo.setOrderStoreCheck(1);
        orderInfo.setOrderStoreCheckTime(LocalDateTime.now());
        return this.updateById(orderInfo);
    }
}
